package com.zl.tby.screen.controller;

import com.zl.tby.core.common.R;
import com.zl.tby.dto.TbyCommandCenterQuery;
import com.zl.tby.dto.TbySmartBoxCenterQuery;
import com.zl.tby.dto.TbySmartBoxHistoryQuery;
import com.zl.tby.model.TbyCommandCenter;
import com.zl.tby.model.TbySmartBoxCenter;
import com.zl.tby.model.TbySmartBoxHistory;
import com.zl.tby.service.ITbyCommandCenterService;
import com.zl.tby.service.ITbySmartBoxCenterService;
import com.zl.tby.service.ITbySmartBoxHistoryService;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.validation.annotation.Valid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 智能箱大屏接口
 * @author changpeng
 * @since 2025/10/15 9:08
 */
@Valid
@Controller
@Mapping("/smart_box_screen")
public class TbySmartBoxScreenController {

    @Inject
    private ITbySmartBoxHistoryService tbySmartBoxHistoryService;
    @Inject
    private ITbyCommandCenterService tbyCommandCenterService;
    @Inject
    private ITbySmartBoxCenterService tbySmartBoxCenterService;

    /**
     * 历史数据曲线
     * @param query: 查询条件
     * @return 结果
     */
    @Mapping(value = "/statistic_charts", method = MethodType.GET)
    public R<List<TbySmartBoxHistory>> statisticCharts(TbySmartBoxHistoryQuery query) {
        return R.ok(tbySmartBoxHistoryService.statisticList(query));
    }

    /**
     * 获取指挥中心，内含指挥中心关联的智能箱
     * @return
     */
    @Mapping(value = "/command_center", method = MethodType.GET)
    public R<List<TbyCommandCenter>> commandCenter() {
        List<TbyCommandCenter> centerList = this.tbyCommandCenterService.list(new TbyCommandCenterQuery());
        List<TbySmartBoxCenter> boxList = this.tbySmartBoxCenterService.list(new TbySmartBoxCenterQuery());
        Map<Long, List<Long>> map = new HashMap<>();
        for (TbySmartBoxCenter box : boxList) {
            if (box.getCenterId() == null) {
                continue;
            }
            List<Long> list = map.get(box.getCenterId());
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(box.getId());
            map.put(box.getCenterId(), list);
        }
        for (TbyCommandCenter center : centerList) {
            List<Long> list = map.get(center.getId());
            if (list == null || list.size() == 0) {
                center.setSmartBoxSns(" ");
            } else {
                center.setSmartBoxSns(list.stream().map(String::valueOf).collect (Collectors.joining (",")));
            }
        }
        return R.ok(centerList);
    }
}
